package com.qfedu.springmvc02.controller;

import com.github.pagehelper.PageInfo;
import com.qfedu.springmvc02.entity.User;
import com.qfedu.springmvc02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * @author zhang
 * @Title: commonValidateAdd
 * @date : 2022/5/4 15:22
 */
@Controller
@SessionAttributes({"user"})
public class LoginController {
    @Autowired
    UserService userService;

    // @PostMapping 这个注解的意思是只能接收post请求
    @PostMapping( value = "/login",produces = "text/html;charset=utf-8")
    public String login(User user, Model model,String code, HttpServletRequest request){
        // 先获取session 中存的验证码，跟用户传入的验证码进行比较 如果不一致 直接返回验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (Objects.equals(captcha,code)){
            // 调用业务层进行登录
            User login = userService.login(user.getName(), user.getPassword());
            if (Objects.nonNull(login)) {
                //登录成功
                model.addAttribute("user",user);
                // 查询所有用户，返回到页面进行显示
                PageInfo<User> pageInfo = userService.selectAllUser(1, 10);
                model.addAttribute("PageInfo",pageInfo);
                return "wecome";
            }else {
                //登录失败
                model.addAttribute("error","用户名或密码错误");
            }
        }else {
            // 验证码输入错误
            model.addAttribute("error","验证码错误");
        }
        return "index";
    }
}
